'use strict';

const express = require('express');
const dbutility = require('../../common/dbutility');
const gputility = require('../../common/gputility');
const utility = require('../../common/utility');
const logger = require('../../common/logutility').logger('regCouInp');
let router = express.Router();

router.get('/', function(req, res) {
    gputility.excuteGP(getGP(req, res));
});

router.post('/', function(req, res) {
    gputility.excuteGP(postGP(req, res));
});

function* getGP(req, res) {
    try {
        res.render('./adm/regCouInp', req.session.couReg);
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

function* postGP(req, res) {
    try {
        let couTel = req.body.couTel;
        let cou = yield dbutility.couModel.getCouByCouTel(couTel);
        if (cou) {
            req.session.couReg = null;
            let pageData = req.body;
            pageData.errorInfo = '该用户已经存在！';
            res.render('./adm/regCouInp', pageData);
        } else {
            req.session.couReg = {};
            req.session.couReg.couName = req.body.couName;
            req.session.couReg.couTel = req.body.couTel;
            req.session.couReg.couCmp = req.body.couCmp;
            req.session.couReg.couPwd = utility.encrypt('123456');
            res.redirect('/regCouConf');
        }
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

module.exports = router;